package com.oedtech.esl.service;

import com.oedtech.esl.model.sys.Role;
import com.oedtech.esl.model.sys.User;
import com.oedtech.esl.repository.sys.RoleDao;
import com.oedtech.esl.repository.sys.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户权限处理业务
 */
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user=userDao.findByUsername(s);

        List<Role>roleCodes=roleDao.findRole(s);
        if (user==null){
            throw new UsernameNotFoundException("username does not exists");
        }

        return new Users(user,roleCodes);
    }
}

class Users extends User implements UserDetails{

    private List<Role> roles;

    public Users() {
    }
    public Users(User user) {
        setId(user.getId());
        setUsername(user.getUsername());
        setPassword(user.getPassword());
       setRemark(user.getRemark());
       setStatus(user.getStatus());
       setExpireTime(user.getExpireTime());
    }
    public Users(User user,List<Role>roles) {
        setId(user.getId());
        setUsername(user.getUsername());
        setPassword(user.getPassword());
        setRemark(user.getRemark());
        setStatus(user.getStatus());
        setExpireTime(user.getExpireTime());
        this.roles=roles;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        for(Role role:roles){
            auths.add(new SimpleGrantedAuthority(role.getRoleCode()));

        }
//        auths.add(new SimpleGrantedAuthority("ADMIN"));
        return auths;
    }

    @Override
    public boolean isAccountNonExpired() {

        if(this.getExpireTime()==null||this.getExpireTime().getTime()-System.currentTimeMillis()<=0){
            return false;
        }
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        if(this.getStatus()==0){
            return true;
        }

        return false;
    }
}